package com.keelau.ui.swing;

import com.keelau.idao.model.AliCatalog;
import com.keelau.jxbrowser.ButtonTabComponent;
import com.keelau.jxbrowser.FxBrowserContextMenu;
import com.keelau.utils.ValidateTools;
import com.teamdev.jxbrowser.chromium.*;
import com.teamdev.jxbrowser.chromium.events.*;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.inject.Named;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.*;

import static com.teamdev.jxbrowser.chromium.LoggerProvider.*;

public class FxBrowerUI {


    private JPanel browerPanel;
    private JTextField textField1;

    private JButton BtnGo;
    private JButton btnCrawler;

    @Inject
    MainForm mainForm;


    //Logger logger = LoggerFactory.getLogger(FxBrowerUI.class);

    JTabbedPane jTabbedPane = new JTabbedPane();

    JDesktopPane jDesktopPane;

    Browser curBrowser;

    public static ArrayList<Browser> browserArrayList = new ArrayList<Browser>();

    public JFrame getFrame() {
        return frame;
    }

    JFrame frame;

    public FxBrowerUI() {
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);
        //logger.info("new FX Browser");
        initUI();
    }

    public void initUI() {

        //view = new BrowserView(browser);
        //view.setPreferredSize(new Dimension(900, 900));

        //region DescktopPane JinternalFrame
        //jDesktopPane  = new JDesktopPane();
       // JInternalFrame jInternalFrame = createInternalFrame(browser,"","www.baidu.com",0);
        //jDesktopPane.add(jInternalFrame);
        //jDesktopPane.setToolTipText("test deskpane");
        //jDesktopPane.getDesktopManager().maximizeFrame(jInternalFrame);
        //endregion


        createTabBrowser(null,"www.baidu.com");

        //browerPanel.setSize(800,900);
        //browerPanel.add(jDesktopPane,BorderLayout.CENTER);//view, BorderLayout.CENTER);
        browerPanel.add(jTabbedPane);

        frame = new JFrame("FxBrowerUI");
        frame.setContentPane(browerPanel);
        frame.setPreferredSize(new Dimension(1000,900));
        frame.setExtendedState(Frame.MAXIMIZED_BOTH);
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); //EXIT_ON_CLOSE);
        addListenter(frame);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {

            }
        });
        //frame.setVisible(true);

    }

    public void addListenter(Frame frame) {

        BtnGo.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (ValidateTools.isUrl(textField1.getText())) {
                    createTabBrowser(null,textField1.getText());
                } else {
                    JOptionPane.showMessageDialog(null,
                            "非法URL", "Sorry~", JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        textField1.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == 10) {
                    BtnGo.doClick();
                }
            }
        });
        btnCrawler.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                doCrawler();
                // listModel.addElement("test test");
            }
        });
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
            /*    if (!browser.isDisposed()) {
                    browser.dispose();
                }*/
                super.windowClosing(e);
            }
        });
    }

    public void addBrowserListener(Browser browser,int index){
        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    printFramesHierarchy(event.getBrowser(), Browser.MAIN_FRAME_ID);
                }
                String title = browser.getTitle();
                // if(title.length()>10)
                //   title = title.substring(10);
                jTabbedPane.setTitleAt(index,browser.getTitle());
            }
        });

        addbrowserPopWindowHandler(browser);
    }

    public void addbrowserPopWindowHandler(Browser browser){
        browser.setPopupHandler(new PopupHandler() {
            public PopupContainer handlePopup(PopupParams params) {
                return new PopupContainer() {
                    public void insertBrowser(final Browser browser, final Rectangle initialBounds) {
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                               /* JInternalFrame internalFrame =createInternalFrame(browser,"","",0);
                                jDesktopPane.add(internalFrame);
                                try {
                                    internalFrame.setMaximum(true);
                                } catch (PropertyVetoException e) {
                                    e.printStackTrace();
                                }*/
                                createTabBrowser(browser,"");
                            }
                        });
                    }
                };
            }
        });
    }

    public  void doCrawler(){
        DefaultListModel defaultListModel = (DefaultListModel) mainForm.getList1().getModel();
        AliCatalog aliCatalog = new AliCatalog();
        aliCatalog.setName("test2");
        aliCatalog.setId(3L);
        defaultListModel.addElement(aliCatalog);
        mainForm.getList1().setModel(defaultListModel);
        int index = jTabbedPane.getSelectedIndex();
        String title = "";

        title = browserArrayList.get(index).getTitle();
        JOptionPane.showMessageDialog(getFrame(),"tab index:" + index
                +"; broswer title:" + title);
       // String html = browser.getHTML();
        //logger.info(html);
    }

    public  void printFramesHierarchy(Browser browser, long parentFrameId) {
        List<Long> childFrameIds = browser.getFramesIds(parentFrameId);
        for (Long childFrameId : childFrameIds) {
            //logger.info("Child Frame: " + childFrameId );//+ ", HTML: " + browser.getHTML(childFrameId));
            printFramesHierarchy(browser, childFrameId);
        }
    }

    public void  createTabBrowser(Browser browser,String url){
        BrowserView view=null;
//        DOMDocument document = browser.getDomDocument();
        if(browser==null){
            browser = new Browser();
            view = new BrowserView(browser);
            browser.setContextMenuHandler(new FxBrowserContextMenu(view,this));
            browser.loadURL(url);

        }else{
            view = new BrowserView(browser);
            browser.setContextMenuHandler(new FxBrowserContextMenu(view,this));
        }
        int index = jTabbedPane.getTabCount();

        browserArrayList.add(browser);

        jTabbedPane.insertTab("正在打开窗口……",null,view,"",jTabbedPane.getTabCount());

        jTabbedPane.setTabComponentAt(index,
                new ButtonTabComponent(jTabbedPane,browser));
        jTabbedPane.updateUI();
        addBrowserListener(browser,index);
        //
       // jTabbedPane.addTab(browser.getTitle().substring(10),new BrowserView(browser));
    }


    private  JInternalFrame createInternalFrame(Browser browser,String title, String url, int offset)  {
       // browser = new Browser(BrowserType.LIGHTWEIGHT);
        BrowserView view = new BrowserView(browser);
        if(!url.isEmpty())
        browser.loadURL(url);

        JInternalFrame internalFrame = new JInternalFrame(title, true,true,true,true);
        internalFrame.setContentPane(view);

        internalFrame.setLocation(100 + offset, 100 + offset);
        internalFrame.setSize(400, 400);
        internalFrame.setVisible(true);
        internalFrame.addInternalFrameListener(new InternalFrameAdapter() {
            @Override
            public void internalFrameClosing(InternalFrameEvent e) {
                browser.dispose();
            }
        });
        return internalFrame;
    }

    private static void redirectLogMessagesToFile(Logger logger, String logFilePath)
            throws IOException {
        FileHandler fileHandler = new FileHandler(logFilePath);
        fileHandler.setFormatter(new SimpleFormatter());

        // Remove default handlers including console handler
        for (Handler handler : logger.getHandlers()) {
            logger.removeHandler(handler);
        }
        logger.addHandler(fileHandler);
    }

    public static void main(String[] args) throws IOException {

        setLevel(Level.ALL);

        // Redirect Browser log messages to jxbrowser-browser.log
       /* redirectLogMessagesToFile(getBrowserLogger(),
                "D:/jxbrowser-browser.log");

        // Redirect IPC log messages to jxbrowser-ipc.log
        redirectLogMessagesToFile(getIPCLogger(),
                "D:/jxbrowser-ipc.log");

        // Redirect Chromium Process log messages to jxbrowser-chromium.log
        redirectLogMessagesToFile(getChromiumProcessLogger(),
                "D:/jxbrowser-chromium.log");
*/

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                FxBrowerUI fxBrowerUI = new FxBrowerUI();
                fxBrowerUI.getFrame().setVisible(true);
            }
        });

    }

    /* public static void main(String[] args) {


        JFrame frame = new JFrame();
        frame.add(browerPanel, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setVisible(true);

        browser.loadURL("http://www.baidu.com");
    }*/
}
